package help

import (
	"time"

	"github.com/dgrijalva/jwt-go"
)

const JWTKEY string = "liyanjun"

type Claims struct {
	Id       uint   `json:"id"`
	UserName string `json:"user_name"`
	jwt.StandardClaims
}

func GenerateToken(id uint, user_name string) (string, error) {
	now_time := time.Now()
	expire_time := now_time.Add(24 * time.Hour)
	claims := Claims{
		Id:       id,
		UserName: user_name,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expire_time.Unix(),
			IssuedAt:  now_time.Unix(),
			Issuer:    "demo",
		},
	}
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString([]byte(JWTKEY))
	return token, err
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(JWTKEY), nil
	})
	if tokenClaims != nil {
		//类型断言
		claims, ok := tokenClaims.Claims.(*Claims)
		if ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	return nil, err
}
